package ext.mango.base;

import java.io.File;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.Properties;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public final class Messages {
    
    private static final String RES_CN = "ext/mango/res/cn";
    private static final Properties MSG_CN = new Properties();
    
    public static final void load() {
        try {
            loadRes(MSG_CN, RES_CN);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static final void loadRes(Properties prop, String res) throws Exception {
        URL url = Thread.currentThread().getContextClassLoader().getResource(res);
        File dir = new File(url.getFile());
        loadRes(prop, dir);
    }

    private static void loadRes(Properties prop, File file) throws Exception{
        if(file.isDirectory() && !file.getName().equals(".svn")) {
            File[] fs = file.listFiles();
            if (fs != null) {
                for(File f : fs) {
                    loadRes(prop, f);
                }
            }
        }
        else if (file.isFile()) {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(file);
            Element e = doc.getRootElement();
            @SuppressWarnings("unchecked")
            Iterator<Element> iter = e.elementIterator("string");
            while(iter.hasNext()) {
                Element string = iter.next();
                String id = string.attributeValue("id");
                String value = string.getText();
                prop.setProperty(id, value);
            }
        }
    }

    private Messages() {
    }

    public static String getString(String language, String key) {
        String ret = "";
        if(Const.LANG_CN.equals(language)) {
            ret = MSG_CN.getProperty(key);
        }
        return ret;
    }
    
    public static String getString(String language, String key, Object...params) {
        String ret = "";
        if(Const.LANG_CN.equals(language)) {
            ret = MessageFormat.format(MSG_CN.getProperty(key), params);
        }
        return ret;
    }
}
